function postJson(url, param, success, failed) {
    ajaxJson("post", url, param, success, failed);
};

function postRJson(url, param, success, failed) {
    ajaxJson("post", url, param, success, failed, {contentType: 'application/json'});
};

function postAJson(url, param, success, failed) {
    ajaxJson("post", url, param, success, failed, {traditional: true});
};

function postJsonNotLayuiLoad(url, param, success, failed) {
    $.post(url, param,
        function (data, status) {
            try {
                if ('success' != status) {
                    layer.msg('服务器错误！请火速联系系统管理员！' + data.data, {
                        time: 30000,
                        btn: ['确定']
                    });
                    return;
                }

                if (data.ret_code > 0) {
                    if (success) {
                        success(data);
                    } else {
                        console.error('操作成功！', {icon: 6});
                    }
                } else {
                    if (data.status == 302) {
                        window.location.href = data.location;
                        return;
                    }
                    if (failed) {
                        failed(data);
                    } else {
                        console.error('操作失败！' + data.data, {icon: 5});
                    }
                }
            }
            catch (err) {
                throw err;
            }
        }, 'json');
};

/* loading表示等待条引用计数 */
var loading = 0;
function ajaxJson(type, url, param, success, failed, params) {
    var layer = layui.layer;

    var ajaxData = {
        type: type,
        url: url,
        data: param,
        dataType: "json",
        success: function (data) {
            loading--;
            if(loading == 0)
                layer.closeAll('loading');
            if (data.ret_code > 0) {
                if (success) {
                    success(data);
                } else {
                    layer.alert('操作成功！', {icon: 6});
                }
            } else {
                if (data.status == 302) {
                    window.location.href = data.location;
                    return;
                }
                else if (failed) {
                    failed(data);
                } else {
                    layer.alert('操作失败！' + data.data, {icon: 5});
                }
            }
        },
        error: function (data) {
            loading--;
            if(loading == 0)
                layer.closeAll('loading');
            layer.msg('服务器错误！请火速联系系统管理员！' + data.data, {
                time: 30000,
                btn: ['确定']
            });
            return;
        }
    };

    if (params) {
        for (var key in params) {
            ajaxData[key] = params[key];
        }
    }

    if(layer == null || layer == undefined){
        layui.use(['layer'],function () {
            layer = layui.layer;
            if(loading == 0)
                layer.load(2);
            loading++;
            $.ajax(ajaxData);
        })
    }else{
        if(loading == 0)
            layer.load(2);
        loading++;
        $.ajax(ajaxData);
    }

}

$.extend({
    Object: {
        count: function (p) {
            p = p || false;

            return $.map(this, function (o) {
                if (!p) return o;

                return true;
            }).length;
        }
    }
});

$.fn.extend({
    initForm: function (options) {
        //默认参数
        var defaults = {
            jsonValue: "",
            isDebug: false   //是否需要调试，这个用于开发阶段，发布阶段请将设置为false，默认为false,true将会把name value打印出来
        }
        //设置参数
        var setting = $.extend({}, defaults, options);
        var form = this;
        jsonValue = setting.jsonValue;
        //如果传入的json字符串，将转为json对象
        if ($.type(setting.jsonValue) === "string") {
            jsonValue = $.parseJSON(jsonValue);
        }
        //如果传入的json对象为空，则不做任何操作
        if (!$.isEmptyObject(jsonValue)) {
            var debugInfo = "";
            $.each(jsonValue, function (key, value) {
                //是否开启调试，开启将会把name value打印出来
                if (setting.isDebug) {
                    alert("name:" + key + "; value:" + value);
                    debugInfo += "name:" + key + "; value:" + value + " || ";
                }
                var formField = form.find("[name='" + key + "']");
                if ($.type(formField[0]) === "undefined") {
                    if (setting.isDebug) {
                        alert("can not find name:[" + key + "] in form!!!");    //没找到指定name的表单
                    }
                } else {
                    var fieldTagName = formField[0].tagName.toLowerCase();
                    if (fieldTagName == "input") {
                        if (formField.attr("type") == "radio") {
                            $("input:radio[name='" + key + "'][value='" + value + "']").attr("checked", "checked");
                        } else {
                            formField.val(value);
                        }
                    } else if (fieldTagName == "select") {
                        //do something special
                        formField.val(value);
                    } else if (fieldTagName == "textarea") {
                        //do something special
                        formField.val(value);
                    } else {
                        formField.val(value);
                    }
                }
            })
            if (setting.isDebug) {
                alert(debugInfo);
            }
        }
        return form;    //返回对象，提供链式操作
    }
});

/*文件上传方法，带有进度条*/
function postUpload(url, params, onProgress, success, failed) {
    layer.load(2);
    var paramsBody;
    if (params instanceof FormData) {
        paramsBody = params;
    } else {
        paramsBody = new FormData();
        for (var key in params) {
            paramsBody.append(key, params[key]);
        }
    }
    upload(url, {
        method: 'post',
        body: paramsBody
    }, onProgress)
        .then(function (data) {
            layer.closeAll('loading');
            if (data.ret_code > 0) {
                if (success) {
                    success(data);
                } else {
                    layer.alert('操作成功！', {icon: 6});
                }
            } else {
                if (failed) {
                    failed(data);
                } else {
                    layer.alert('操作失败！' + data.data, {icon: 5});
                }
            }
        })
        .catch(function (error) {
            layer.closeAll('loading');
            layer.msg('服务器错误！请火速联系系统管理员！' + error.data, {
                time: 30000,
                btn: ['确定']
            });
        });
}

function upload(url, opts, onProgress) {
    return new Promise(function (res, rej) {
        var xhr = new XMLHttpRequest();
        xhr.open(opts.method || 'get', url);
        for (var k in opts.headers || {})
            xhr.setRequestHeader(k, opts.headers[k]);
        xhr.onload = function (e) {
            if (e.target.status < 200 || e.target.status >= 300) {
                res(new CommonException(e.target.status, e.target.responseText));
            } else {
                res(JSON.parse(e.target.responseText))
            }
        };
        xhr.onerror = rej;
        xhr.withCredentials = true;
        if (xhr.upload && onProgress)
            xhr.upload.onprogress = onProgress; // event.loaded / event.total * 100 ; //event.lengthComputable
        xhr.send(opts.body);
    });
}

function CommonException(ret_code, data) {
    var ret;
    try {
        ret = JSON.parse(data);
    } catch (err) {
        ret = data;
    }
    this.data = ret.data ? ret.data : data;
    this.ret_code = ret.ret_code ? ret.ret_code : ret_code;
}


/* 获取路径中的参数,不依赖jquery*/
function getUrlParam(name) {
    return getUrlParamByLocation(window.location.search, name);
}

function getUrlParamByLocation(location, name) {
    console.log(location);
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = location.substr(1).match(reg);
    if (r != null) return decodeURI(r[2]);
    return null;
}